<?php
/**
 * @Author: king
 * @Date:   2019-01-14 21:23:07
 * @Last Modified by:   king
 * @Last Modified time: 2019-02-17 21:29:23
 */
namespace App\Models\Api;

use App\Exceptions\ApiException;
use App\Models\Api\Base;
use Cache;
class WechatRecode extends Base
{
    protected $table = 'wechat_recode';

    const CACHE_TIME = 86400 * 7;

    /**
     * 获取当前用户的微信档案列表
     * @param array $map
     * @return array
     */
    public function getWechatRecodeLists($map = [])
    {
        $uid = $map['uid'];
        $page = $map['page'];

        $recode_list_ids = false;

        if ($this->cache_on >= 1)
        {
            $recode_list_ids = Cache::get('wechat_recode_lists_' . $uid);
        }

        // 获取当前微信档案列表id
        if ($recode_list_ids === false)
        {
            try
            {
                $data = $this
                    ->select('id')
                    ->where(['uid' => $uid, 'status' => 0])
                    ->orderBy('create_time', 'DESC')
                    ->get();
                $data = json_decode(json_encode($data, true), true);

                // 将档案id组成字符串
                if (!empty($data)) foreach ($data as $acl) $recode_list_ids .= $acl['id'] . ',';

                // 缓存档案id,根据档案id
                if ($this->cache_on >= 1)
                {
                    Cache::set('wechat_recode_lists_' . $uid, $recode_list_ids, self::CACHE_TIME);
                }
            }
            catch (\Exception $e)
            {
                $recode_list_ids = '';// 档案列表默认为空
            }
        }
        // 将微信档案id转为数组
        $recode_list_ids = explode(',', $recode_list_ids);

        $per_page = 10;// 当前文章评论每页显示数量
        // 去除数组最后一个元素
        array_pop($recode_list_ids);

        // 统计有多少微信档案
        $total = count($recode_list_ids);
        //获取数据分页信息
        $data_list = getPaginatorData($total, $page, $per_page);

        //获取分页后的微信档案id数组
        $recode_list_id = array_slice($recode_list_ids, $data_list['start'], $per_page);

        unset($data_list['start']);
        unset($data_list['end']);


        // 根据当前页微信档案id获取所需的档案信息
        if (!empty($recode_list_id))
        {
            $ac_ids = '';
            $temp = [];

            // 从缓存档案内容,根据档案id
            foreach ($recode_list_id as $ac_id)
            {
                if ($this->cache_on >= 1)
                {
                    // 根据档案id 获取档案内容
                    $temp[$ac_id] = Cache::get('wechat_recode_' . $ac_id);
                } else
                {
                    // 缓存未开启时，默认从数据库获取
                    $temp[$ac_id] = false;
                }
                // 档案内容未缓存，等待从数据库中获取
                if ($temp[$ac_id] === false)
                {
                    $ac_ids .= ',' . $ac_id;
                }
            }

            // 从数据库获取档案内容
            if ($ac_ids != '' || strlen($ac_ids) > 0)
            {
                // 去掉开头的,
                $ac_ids = substr($ac_ids, 1);
                try
                {
                    $data = $this
                        ->select('id','name','sex as type','avatar','unionid','sun_moon_asc','birth_time','birth_place','longitude','latitude')
                        ->whereIn('id',$ac_ids)
                        ->where(['uid' => $uid, 'status' => 0])
                        ->get();

                    $recodes = json_decode(json_encode($data, true), true);
                }
                catch (\Exception $e)
                {
                    $recodes = [];
                }

                if (!empty($recodes))
                {
                    foreach ($recodes as $c)
                    {
                        // 将档案内容缓存
                        if ($this->cache_on >= 1)
                        {
                            Cache::set('wechat_recode_' . $c['id'], $c, self::CACHE_TIME);
                        }
                        // 将数据库查出来的内容 写入到数组中为空的部分
                        $temp[$c['id']] = $c;
                    }
                }
            }

            foreach ($temp as $item)
            {
                $data_list['data'][] = $item;
            }
        }

        return $data_list;

    }

    /**
     * 获取当前微信档案的信息
     * @param array $map
     * @return array|bool|mixed|\PDOStatement|string|\think\Model
     * @throws ApiException
     */
    public function getWechatRecode($map = [])
    {

        $wid = $map['wid'];

        $data = false;

        if ($this->cache_on >= 1 && Cache::has('wechat_recode_' . $wid))
        {
            $data = Cache::get('wechat_recode_' . $wid);
        }

        if ($data === false)
        {
            try
            {
                $data = $this
                    ->select('id','name','sex as type','avatar','unionid','sun_moon_asc','birth_time','birth_place','longitude','latitude')
                    ->where('id', $wid)
                    ->findOrFail();
                $data = json_decode(json_encode($data, true), true);

                if ($this->cache_on >= 1)
                {
                    Cache::set('wechat_recode_' . $wid, $data, self::CACHE_TIME);
                    Cache::set('wechat_recode_' . $data['unionid'], $wid, self::CACHE_TIME);
                }
            }
            catch (\Exception $e)
            {
                \Log::info('微信档案查询失败：'.$e->getMessage());

                $this->error = '微信档案不存在！';
                $data = false;
            }
        }

        return $data;
    }

    /**
     * 获取当前微信档案的信息
     * @param array $map
     * @return array|bool|mixed|\PDOStatement|string|\think\Model
     */
    public function getWechatRecodeWithUnionid($map = [])
    {
        $uid = $map['uid'];
        $unionid = $map['unionid'];

        $data = false;

        if ($this->cache_on >= 1)
        {
            $data = Cache::get('wechat_recode_' . $uid . '_' . $unionid);
            if ($data != false)
            {
                $data = Cache::get('wechat_recode_' . $data);
            }
        }

        if ($data === false)
        {
            try
            {
                $data = $this
                    ->select('id','name','sex as type','avatar','unionid','sun_moon_asc','birth_time','birth_place','longitude','latitude')
                    ->where(['uid' => $uid, 'unionid' => $unionid])
                    ->findOrFail();

                $data = json_decode(json_encode($data, true), true);

                if ($this->cache_on >= 1)
                {
                    Cache::set('wechat_recode_' . $uid . '_' . $data['unionid'], $data['id'], self::CACHE_TIME);
                    Cache::set('wechat_recode_' . $data['id'], $data, self::CACHE_TIME);
                }
            }
            catch (\Exception $e)
            {
                $data = false;
            }
        }

        return $data;
    }

    /**
     * 获取当前微信档案的信息
     * @param array $map
     * @return array|bool|mixed|\PDOStatement|string|\think\Model
     */
    public function getWechatRecodeByUnionid($map = [])
    {
        $unionid = $map['unionid'];

        $data = false;

        if ($this->cache_on >= 1)
        {
            $data = Cache::get('wechat_recode_' . $unionid);
            if ($data != false)
            {
                $data = Cache::get('wechat_recode_' . $data);
            }
        }

        if ($data === false)
        {
            try
            {
                $data = $this
                    ->select('id','name','sex as type','avatar','unionid','sun_moon_asc','birth_time','birth_place','longitude','latitude')
                    ->where(['unionid' => $unionid])
                    ->orderBy('id','DESC')
                    ->findOrFail();

                $data = json_decode(json_encode($data, true), true);

                if ($this->cache_on >= 1)
                {
                    Cache::set('wechat_recode_' . $data['unionid'], $data['id'], self::CACHE_TIME);
                    Cache::set('wechat_recode_' . $data['id'], $data, self::CACHE_TIME);
                }
            }
            catch (\Exception $e)
            {
                $data = false;
            }
        }

        return $data;
    }

    /**
     * 微信档案新增或更新
     * @param $data
     * @return int|mixed|string
     */
    public function insertWechatRecode($data)
    {
        //根据uid和unionid查询这个用户是否在数据库里
        $result = $this->getWechatRecodeWithUnionid(['uid' => $data['uid'], 'unionid' => $data['unionid']]);
        if (!$result)
        {//不在数据库里，那么插入数据
            $data['id'] = $this->insertGetId($data);
        } else
        {//在数据库里，根据页面传过来的值，更新数据库
            if (!empty($data) && !empty($data['type']))
            {
                $data['sex'] = $data['type'];
                unset($data['type']);
            }
            $data['status'] = 0;
            $data['id'] = $result['id'];
            $this->update($data);
        }
        if ($this->cache_on >= 1)
        {
            //因为逻辑里性别用的type 所以这里把sex 转换为type
            $data['type'] = $data['sex'];
            Cache::set('wechat_recode_' . $data['unionid'], $data['id'], self::CACHE_TIME);
            Cache::set('wechat_recode_' . $data['id'], $data, self::CACHE_TIME);
            Cache::forget('wechat_recode_lists_' . $data['uid']);
        }

        return $data['id'];
    }
}